<template>
  <div class="docContent">
    <a-layout>
      <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
        <h3 v-if="level1.length === 0">好像没有文档哦，快去添加吧~</h3>
        <a-row>
          <a-col :span="6">
            <a-tree
                v-if="level1.length > 0"
                :tree-data="level1"
                @select="onSelect"
                :replaceFields="{title: 'name', key: 'id', value: 'id'}"
                :defaultExpandAll="true"
                :defaultSelectedKeys="defaultSelectedKeys"
            >
            </a-tree>
          </a-col>
          <a-col :span="18">
            <div>
              <h2>{{doc.name}}</h2>
              <div>
                <span>阅读数：{{doc.viewCount}}</span> &nbsp; &nbsp;
                <span>点赞数：{{doc.voteCount}}</span>
              </div>
              <a-divider style="height: 2px; background-color: #9999cc"/>
            </div>
            <div class="wangeditor" :innerHTML="html"></div>
            <div class="vote-div">
              <a-button type="primary" shape="round" :size="'large'" @click="vote">
                <template #icon><LikeOutlined /> &nbsp;点赞：{{doc.voteCount}} </template>
              </a-button>
            </div>

            <!-- 展示评论 -->
            <div id="showComment">
              <a-list
                  v-if="comments.length"
                  :data-source="comments"
                  :header="`${comments.length} ${comments.length > 1 ? '评论' : '评论'}`"
                  item-layout="horizontal"
              >
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-comment
                        :author="item.username"
                        :avatar="item.avatar"
                        :content="item.content"
                        :datetime="item.createTime"
                    />
                  </a-list-item>
                </template>
              </a-list>
            </div>

            <!-- Rate评分功能 -->
            <div id="rate">
              看完这篇文章是否有收获： <a-rate v-model:value="rateValue" /><span class="ant-rate-text">{{ desc[rateValue - 1] }}</span>
              <p></p>
            </div>

            <!-- 评论功能 -->
            <div id="comment">
              <a-textarea v-model:value="CommentContent"
                          :auto-size="{minRows: 7, maxRows: 7}"
                          placeholder="在这留下您的宝贵意见~"
                          allow-clear
              />
              <div id="commentButton">
                <a-button type="primary" size="middle" @click="submit">发送</a-button>
              </div>
            </div>

          </a-col>
        </a-row>
      </a-layout-content>
    </a-layout>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, createVNode,reactive,onUpdated,onBeforeUpdate} from 'vue';
import axios from 'axios';
import {message} from 'ant-design-vue';
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";

// 引入并注册dayjs模块，好像是轻量级js库，用来显示时间的
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import utc from 'dayjs/plugin/utc';
dayjs.extend(relativeTime);
dayjs.extend(utc);


export default defineComponent({
  name: 'Doc',
  setup() {
    const route = useRoute();
    const docs = ref();
    const html = ref();
    const defaultSelectedKeys = ref();
    defaultSelectedKeys.value = [];

    // 当前选中的文档
    const doc = ref();
    doc.value = {};

    // 定义展示评论用到的comments数组
    type Comment = Record<string, string>; // 好像是定义一个类
    const comments = ref<Comment[]>([]);

    // 定义点击评论提交按钮时的加载状态
    // const submitting = ref<boolean>(false);

    // Rate评分功能，定义一个value
    const rateValue = ref<number>(0);
    const desc = ref<string[]>(['没有收获', '很少', '一般', '收获很多', '非常有收获']);
    // 输入评论时用到的响应式变量
    const CommentContent = ref<string>('')
    const comment1 = ref();
    comment1.value = {}

    // Comment评论功能用到的对象,利用reactive定义comment对象
    const comment = reactive({
      id:null,
      username:'访客',
      content:'',
      rate:0,
      userId:111,
      ebookId:11111,
      pid:1111,
      target:'jxc',
      docName:doc.value.name,
      // datetime:dayjs().fromNow(),
    })
    // 评论功能的点击提交事件
    const submit=()=>{

      comment1.value.id = null;
      comment1.value.username = '访客';
      comment1.value.content = CommentContent.value;
      comment1.value.rate = rateValue.value;
      comment1.value.createTime = dayjs().utc().format("YYYY-MM-DD HH:mm:ss");
      comment1.value.docName = doc.value.name;

      console.log(" dayjs().utc().format()的内容："+ dayjs().utc().format("YYYY-MM-DD HH:mm:ss"));
      console.log("comment1对象的内容："+comment1.value)
      console.log("当前文章的标题："+comment1.value.docName);

      axios.post('/comment/save',comment1.value).then((response) =>{

        const respData = response.data;
        if (respData.success ){
          message.success("提交成功")
        }else {
          message.error(respData.message);
        }
      })
      // 提交内容后，把评论框的内容清空
      CommentContent.value='';

      setTimeout(() => {
        // 提交完成后，获取评论
        console.log("正在更新评论内容");
        getComment();

      }, 300);
    }

    // 获取后端评论信息，前端需要username,avatar,content,datetime
    const getComment = () => {

      axios.get('/comment/list/'+doc.value.name).then((response) =>{
        const data = response.data;

        comments.value = data.content;
        for (let i = 0; i < comments.value.length; i++) {
          comments.value[i].avatar="/image/github_Cover.jpg";
        }
        console.log("comments的值："+JSON.stringify(comments.value));
        console.log("getComment（）执行完毕");
      })
    }
    // 定义定时器
    // setTimeout(() => {
    //   submitting.value = false;
    //
    // }, 500);

    /**
     * 内容查询
     **/
    const handleQueryContent = (id: number) => {
      axios.get("/doc/find-content/" + id).then((response) => {
        const data = response.data;
        if (data.success) {
          html.value = data.content;
        } else {
          message.error(data.message);
        }
      });
    };

    const onSelect = (selectedKeys: any, info: any) => {
      console.log('selected', selectedKeys, info);
      if (Tool.isNotEmpty(selectedKeys)) {
        // 选中某一节点时，加载该节点的文档信息
        doc.value = info.selectedNodes[0].props;
        // 加载内容
        handleQueryContent(selectedKeys[0]);

        // 加载完改节点的文档信息后同时加载该节点文章的评论
        getComment();
      }
    };
    // 当前选中的文档

    /**
     * 一级文档树，children属性就是二级文档
     * [{
     *   id: "",
     *   name: "",
     *   children: [{
     *     id: "",
     *     name: "",
     *   }]
     * }]
     */
    const level1 = ref(); // 一级文档树，children属性就是二级文档
    level1.value = [];

    /**
     * 内容查询
     **/
    // const handleQueryContent = (id: number) => {
    //   axios.get("/doc/find-content/" + id).then((response) => {
    //     const data = response.data;
    //     if (data.success) {
    //       html.value = data.content;
    //     } else {
    //       message.error(data.message);
    //     }
    //   });
    // };

    /**
     * 数据查询
     **/
    const handleQuery = () => {
      axios.get("/doc/all/" + route.query.ebookId).then((response) => {
        const data = response.data;
        if (data.success) {
          docs.value = data.content;

          level1.value = [];
          level1.value = Tool.array2Tree(docs.value, 0);

          if (Tool.isNotEmpty(level1)) {
            // 选中第一个节点（并没有赋值）
            defaultSelectedKeys.value = [level1.value[0].id];
            // 将第一个节点的值查出来
            handleQueryContent(level1.value[0].id);
            // 初始显示文档信息
            doc.value = level1.value[0];
          }
        } else {
          message.error(data.message);
        }
      });
    };


    // 点赞
    const vote = () => {
      axios.get('/doc/vote/' + doc.value.id).then((response) => {
        const data = response.data;
        if (data.success) {
          doc.value.voteCount++;
        } else {
          message.error(data.message);
        }
      });
    };

    onMounted(() => {
      handleQuery();

      setTimeout(() => {
          // 页面打开时，获取当前文章的评论
          console.log("onMounted执行完成后开始执行getComment()");
          console.log("doc.value.name的值："+doc.value.name);
          getComment();

      }, 300);

    });


    return {
      level1,
      html,
      onSelect,
      defaultSelectedKeys,
      doc,
      vote,
      // 评分功能用到的返回值
      // rateValue,
      desc,

      // 评论功能用到的返回值
      comment,
      submit,
      comments,
      getComment,
      rateValue,
      CommentContent,
    }
  }
});
</script>

<style scoped>
/* wangeditor默认样式, 参照: http://www.wangeditor.com/doc/pages/02-%E5%86%85%E5%AE%B9%E5%A4%84%E7%90%86/03-%E8%8E%B7%E5%8F%96html.html */
/* table 样式 */
.wangeditor table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.wangeditor table td,
.wangeditor table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
.wangeditor table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}

/* blockquote 样式 */
.wangeditor blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
.wangeditor code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
.wangeditor pre code {
  display: block;
}

/* ul ol 样式 */
.wangeditor ul, ol {
  margin: 10px 0 10px 20px;
}

/* 和antdv p冲突，覆盖掉 */
.wangeditor blockquote p {
  font-family:"YouYuan";
  margin: 20px 10px !important;
  font-size: 16px !important;
  font-weight:600;
}

/* 点赞 */
.vote-div {
  padding: 15px;
  text-align: center;
}

/* 图片自适应 */
.wangeditor img {
  max-width: 100%;
  height: auto;
}

/* 视频自适应 */
.wangeditor iframe {
  width: 100%;
  height: 400px;
}

/* 将评分功能居中 */
#rate{
  /*text-align: center;*/

}
/*调整评论div块的宽度*/
#comment{
  width: 700px;
  height: 200px;
}

#commentButton{
  padding-top: 10px;
}
#showComment{
  padding-top: 80px;
  padding-bottom: 150px;
}

.docContent{
  margin: 15px 200px 10px;
}
</style>